﻿Imports Windows.Storage
Imports System.Text
Imports System.Threading.Tasks
Imports System.IO

Namespace IO
    Public Module IsolatedStorageHelper
        Public Async Sub WriteFileToIsolatedStorage(fileName As String, fileContent As String, encode As Encoding)
            Dim applicationFolder = ApplicationData.Current.LocalFolder
            Dim storageFile = Await applicationFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting)
            Using s = Await storageFile.OpenStreamForWriteAsync
                Dim content = encode.GetBytes(fileContent)
                Await s.WriteAsync(content, 0, content.Length)
            End Using
        End Sub

        Public Sub WriteFileToIsolatedStorage(fileName As String, fileContent As String)
            WriteFileToIsolatedStorage(fileName, fileContent, Encoding.UTF8)
        End Sub

        Public Async Function ReadFileFromIsolatedStorage(fileName As String, encode As Encoding) As Task(Of String)
            Dim applicationFolder = ApplicationData.Current.LocalFolder
            Dim storageFile = Await applicationFolder.GetFileAsync(fileName)
            Using s = Await storageFile.OpenStreamForReadAsync
                Using reader As New StreamReader(s, encode)
                    Return Await reader.ReadToEndAsync
                End Using
            End Using
        End Function

        Public Async Function ReadFileFromIsolatedStorage(fileName As String) As Task(Of String)
            Return Await ReadFileFromIsolatedStorage(fileName, True)
        End Function

        Public Async Function ReadFileFromIsolatedStorage(fileName As String, detectEncodingFromByteOrderMarks As String) As Task(Of String)
            Dim applicationFolder = ApplicationData.Current.LocalFolder
            Dim storageFile = Await applicationFolder.GetFileAsync(fileName)
            Using s = Await storageFile.OpenStreamForReadAsync
                Using reader As New StreamReader(s, detectEncodingFromByteOrderMarks)
                    Return Await reader.ReadToEndAsync
                End Using
            End Using
        End Function
    End Module
End Namespace